// pages/couponCenter/couponCenter.js
const couponService = require('../../../../api/couponService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentStoreInfo: {
      storeId: '',
      storeName: '未获取到门店信息'
    },
    couponList: [],
    loadText: '正在加载中...',
    page: 1,
    pageSize: 10,
    x: 0,
    y: 0,
    scale: 2,
    homeBack: false,
    phone: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    if (app.globalData.storeInfo) {
      this.setData({
        currentStoreInfo: app.globalData.storeInfo
      })
    }
    var pageStack = getCurrentPages()
    console.log(pageStack)
    if (pageStack.length === 1) {
      this.setData({
        homeBack: true
      })
    }
    if (this.options.mobile && this.options.mobile != '' && this.options.mobile != undefined) {
      const mobile = this.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.storeInfo) {
      console.log(app.globalData.storeInfo)
      this.setData({
        currentStoreInfo: {
          storeId: app.globalData.storeInfo.id,
          storeName: app.globalData.storeInfo.name
        }
      })
      this.getCouponList(this.data.page)
    }
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      couponList: [],
      page: 1,
    })
    this.getCouponList(1)
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 获取券列表
   */
  getCouponList: function (page) {
    wx.showLoading({
      title: '加载中',
    })
    const that = this
    let storeId = that.data.currentStoreInfo.storeId
    let postData = {
      page: page,
      pageSize: this.data.pageSize,
      storeIdEquals: storeId
    }
    let couponList = [
      [],
      []
    ]
    couponList[0] = couponService.getCouponActivitiesByFilter(postData).then(res => {
      let tempList = []
      if (res.records && res.records.length > 0) {
        res.records.forEach(item => {
          if (item.status === 'COMMIT') {
            let tempItem = {
              ...item,
              isExternal: false
            }
            tempList.push(tempItem)
          }
        })
      }
      return tempList
    })
    couponList[1] = couponService.getExternalCouponActivities().then(res => {
      let tempList = []
      if (res && res.length > 0) {
        res.forEach(item => {
          if (item.status === 'COMMIT') {
            let tempItem = {
              ...item,
              isExternal: true
            }
            tempList.push(tempItem)
          }
        })
      }
      return tempList
    }).catch(e => {
      return []
    })
    Promise.all(couponList).then(res => {
      console.log(res)
      let tempList = res[0].concat(res[1])
      let newTempList = []
      tempList.forEach(ele => {
        if (ele.rate) {
          ele = {
            ...ele,
            rate: (ele.rate * 10).toFixed(1)
          }
        }
        newTempList.push(ele)
      })
      console.log(newTempList)
      wx.hideLoading()
      that.setData({
        couponList: newTempList
      })
    })
  },
  // 前往券详情页面
  toCouponDetails: function (val) {
    const that = this
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        const isExternal = val.currentTarget.dataset.external
        if (!isExternal) {
          wx.navigateTo({
            url: '../couponDetails/couponDetails?couponActivityId=' + val.currentTarget.dataset.couponid + '&type=assign&isExternal=' + isExternal
          })
        } else {
          // 外部券无详情不跳转
          wx.showToast({
            title: '该券不能查看',
            icon: 'none',
            duration: 1500
          })
        }
      } else {
        that.handlePopupPhone()
      }
    } else {
      wx.showToast({
        title: '您还没有登录，请点击头像授权登陆~',
        icon: 'icon',
        duration: 2000,
      })
    }
  },
  toHome: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 领券
  handleCoupon: function (val) {
    const that = this
    const couponId = val.currentTarget.dataset.couponid
    const couponList = that.data.couponList
    var currentCoupon = null
    couponList.forEach(item => {
      if (couponId === item.id) {
        currentCoupon = item
      }
    })
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        if (currentCoupon.service === 'HD') {
          // 外部券 HD
          couponService.createCouponOrder(currentCoupon.dlyCouponActivityId).then(res => {
            console.log(res)
            if (res.status === 'ACQUIRE') {
              wx.showToast({
                title: '领券成功',
                icon: 'none',
                duration: 2000
              })
            } else if (res.status === 'CREATED') {
              let postData = {
                orderId: res.id,
                // payMethod: 'SWIFTPASS'
                payMethod: 'WX_MINI_APP'
              }
              couponService.getCouponPaySign(postData).then(res => {
                console.log(res)
                var resData = JSON.parse(res);
                var sign = JSON.parse(resData.sign)
                console.log(sign)
                if (postData.payMethod === 'WX_MINI_APP') {
                  wx.requestPayment({
                    'timeStamp': sign.timeStamp,
                    'nonceStr': sign.nonceStr,
                    'package': sign.packageValue,
                    'signType': sign.signType,
                    'paySign': sign.paySign,
                    'success': function (res) {
                      wx.showToast({
                        title: '领券成功',
                        icon: 'none',
                        duration: 2000
                      })
                    },
                    'fail': function (res) {
                      console.log('支付失败')
                      console.log(res)
                      if (res.errMsg === 'requestPayment:fail cancel') {
                        wx.showToast({
                          title: '您取消了支付~',
                          icon: 'none',
                          duration: 2000
                        })
                      } else {
                        wx.showToast({
                          title: res.errMsg,
                          icon: 'none',
                          duration: 2000
                        })
                      }
                    }
                  })
                } else if (postData.payMethod === 'SWIFTPASS') {
                  wx.requestPayment({
                    'timeStamp': sign.timeStamp,
                    'nonceStr': sign.nonceStr,
                    'package': sign.package,
                    'signType': sign.signType,
                    'paySign': sign.paySign,
                    'success': function (res) {
                      wx.showToast({
                        title: '领券成功',
                        icon: 'none',
                        duration: 2000
                      })
                    },
                    'fail': function (res) {
                      console.log('支付失败')
                      console.log(res)
                      if (res.errMsg === 'requestPayment:fail cancel') {
                        wx.showToast({
                          title: '您取消了支付~',
                          icon: 'none',
                          duration: 2000
                        })
                      } else {
                        wx.showToast({
                          title: res.errMsg,
                          icon: 'none',
                          duration: 2000
                        })
                      }
                    }
                  })
                }

              }).catch(err => {
                if (err.code === 1) {
                  wx.showToast({
                    title: '领券失败',
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.showToast({
                    title: err.message,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            } else {
              wx.showToast({
                title: res.acquireFailedReason,
                icon: 'none',
                duration: 2000
              })
            }
          }).catch(e => {
            console.log(e)
            wx.showToast({
              title: e.message,
              icon: 'none',
              duration: 2000
            })
          })
        } else {
          // 内部券
          if (currentCoupon.balance > 0) {
            let postData = {
              activityId: couponId
            }
            couponService.assign(postData).then(res => {
              console.log(res)
              wx.showToast({
                title: '领券成功',
                icon: 'none',
                duration: 2000
              })
            }).catch(e => {
              console.log(e)
              if (e.code === 17005) {
                wx.showToast({
                  title: '券活动指定的有效期已经过期，不能领取~',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: e.message,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          } else {
            wx.showToast({
              title: '券已经被抢光了哦~',
              icon: 'none',
              duration: 2000
            })
          }
        }
      } else {
        that.handlePopupPhone()
      }
    } else {
      wx.showToast({
        title: '您还没有登录，请点击头像授权登陆~',
        icon: 'icon',
        duration: 2000,
      })
    }
  },

  /**
   * 跳转到门店选择页
   */
  toSelectStore: function () {
    wx.navigateTo({
      url: '../../index/selectStore/selectStore',
    })
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          hasUserInfo: false,
        })
        self.handlePopupPhone()
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})